package com.jy.modules.cims.common.controller;

import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmExcelDictionaryService;
import com.jy.modules.cims.component.common.service.TCMmExcelTemplateService;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.data.common.dto.TCMmExcelDictionaryDTO;
import com.jy.modules.cims.data.common.dto.TCMmExcelTemplateDTO;
import com.jy.modules.platform.sysdict.impl.SysDictAPImpl;
import com.jy.platform.core.message.QueryReqBean;

@Controller
@Scope("prototype")
@RequestMapping("/excelTools")
public class ExcelToolsController {
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.ExportAndImport")
	private ExportAndImport<?> exportAndImportService;
	
	//EhCacheManager ehcacheManager;
	
	@Autowired
	private SysDictAPImpl sysDictAPI;
	
	@Autowired
	private TCMmExcelTemplateService serviceExcelTemplate;
	
	@Autowired
	private TCMmExcelDictionaryService serviceExcelDictionary;
	
	/**
	 * @throws Exception
	 * 
	 * @Description 数据明细导入
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/ImportDataName")
	public void publicImportMothed(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Writer out = response.getWriter();
		Map<String, Object> result = new HashMap<String, Object>();
		UUID importDataId = UUID.randomUUID();
		String className = request.getParameter("className");
		String contractCode = request.getParameter("contractCode");
		String templateType = request.getParameter("dealType");
		//String dataPath = request.getParameter("dataPath");
		// 获取文件流
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		FileItem fileItems = file.getFileItem();
		String fileName = fileItems.getName();
		InputStream inputStream = file.getInputStream();
		
		Class<?> classObject = Class.forName(className);
		Map<String, Map> excelColumnsConvertMap = this.queryDictDetailByTempalteMap(contractCode, templateType);
		try {
			
			List<?> DealList = exportAndImportService.excelImport(inputStream, fileName, contractCode,templateType, classObject, excelColumnsConvertMap);
			//zhoupeng 债权受让导入时未做条数的限制，应限制1000条 
			if(DealList.size()>1000){
				throw new Exception("导入数据大于1000条，导入失败");
			}
			
			request.getSession().setAttribute(importDataId.toString(), DealList);
			
			// 回显数据
			result.put("status", "ok");
			result.put("importDataId", importDataId);
			out.write(JSON.toJSONString(result));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.put("status", "error");
			result.put("errorMassage", e.getMessage());
			out.write(JSON.toJSONString(result));
		}
		
	}
	
	/**
	 * 数据字典码值取名称
	 * 
	 * @Title getDictDetailName
	 * @Description TODO
	 * @param dict_code
	 * @param detail_value
	 * @return String
	 * @throws
	 */
	private Map<String, String> getDictDetailValue(String dict_code) {
		
		List<Map> dictData=null;
		Map<String, String> dictDataDetail = new HashMap<String, String>();
		if (!SimpleStringUtils.isBlank(dict_code)) {
			
			//{ORDERBY=1, DICVALUE=1, DICNAME=资金周转}
			dictData = sysDictAPI.getDictByKey(dict_code);
			
			for(int i=0;i<dictData.size();i++){
				Map dictMap= dictData.get(i);
				dictDataDetail.put(dictMap.get(CimsConstant.DICT_DATA_NAME).toString(), dictMap.get(CimsConstant.DICT_DATA_CODE).toString());				
			}
		}
		return dictDataDetail;
	}
	
	private Map<String, Map> queryDictDetailByTempalteMap (String contractCode,String templateType) throws Exception{
	 	Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("contractCode", contractCode);
        searchParams.put("templateType", templateType);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
        TCMmExcelTemplateDTO templateDTO = serviceExcelTemplate.findTCMmExcelTemplateByContractCodeNotDto(params
                .getSearchParams());
        String templateCode = templateDTO.getTemplateCode();
        TCMmExcelDictionaryDTO dtoExcelDictionaryId = serviceExcelDictionary
                .queryTCMmExcelDictionaryByTemplateCode(templateCode);

        String[] columnCodes = dtoExcelDictionaryId.getColumnCode().split(",");
        //String[] columnNames = dtoExcelDictionaryId.getColumnName().split(",");
        Map<String, Map> excelColumnsConvertMap = new HashMap<String, Map>();
        for(int i=0;i<columnCodes.length;i++){
        	String fieldName = columnCodes[i];
        	Map<String, Object> fieldNameMap = new HashMap<String, Object>();
        	fieldNameMap.put("fieldName", fieldName);
            QueryReqBean fieldNameParams = new QueryReqBean();
            fieldNameParams.setSearchParams(fieldNameMap);
                        
            Map<String, String> dictCodes = serviceExcelTemplate.findDictCodeByContractCode(fieldNameParams
                    .getSearchParams());
            
            String dictCode=null;
            
            if(dictCodes.size()>0){
            	dictCode = dictCodes.get(fieldName.toUpperCase()).toString();
            }
            
            if(dictCode!=null){
            	Map<String,String> dictDataDetail = this.getDictDetailValue(dictCode);
            	excelColumnsConvertMap.put(fieldName, dictDataDetail);
            }
        }
        return excelColumnsConvertMap;
	}
}
